/**
 * @author harry
 * @date 2021/12/6/8:57
 */

package com.ui.group;

import com.controller.GroupController;
import com.pojo.Group;
import com.ui.builder.ButtonBuilder;
import com.ui.builder.ComboboxBuilder;
import com.ui.builder.LabelBuilder;
import com.ui.builder.TextFieldBuilder;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class ModifyGroup extends JFrame implements ActionListener {
    private final JPanel inputPanel = new JPanel();
    private final JPanel buttonPanel = new JPanel();
    private final JLabel chooseLabel = LabelBuilder.makeLabel("选择分组");
    private final JComboBox<Object> valueChoose = ComboboxBuilder.makeCombobox();
    private final JLabel inputLabel = LabelBuilder.makeLabel("新分组名");
    private final JTextField valueInput = TextFieldBuilder.makeTextField(15);
    private final JButton submit = ButtonBuilder.makeButton("确认");
    private final JButton cancel = ButtonBuilder.makeButton("取消");
    private final GroupController groupController = new GroupController();

    public ModifyGroup() {
        super("修改分组");

        List<Group> groupList = groupController.getAllGroups();
        if(groupList == null) {
            JOptionPane.showMessageDialog(null, "获取分组列表失败");
            return;
        }
        for(Group g: groupList) {
            valueChoose.addItem(g.getValue());
        }

        submit.addActionListener(this);
        cancel.addActionListener(this);

        inputPanel.setLayout(new GridLayout(3, 2, 0, 20));
        inputPanel.add(chooseLabel);
        inputPanel.add(valueChoose);
        inputPanel.add(inputLabel);
        inputPanel.add(valueInput);
        inputPanel.add(new JLabel());
        inputPanel.add(new JLabel());

        buttonPanel.setLayout(new GridLayout(1, 2, 30, 0));
        buttonPanel.add(submit);
        buttonPanel.add(cancel);

        this.setLayout(new FlowLayout());
        this.setSize(400, 250);
        this.setLocationRelativeTo(null);
        this.add(inputPanel);
        this.add(buttonPanel);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source == submit) {
            String oldGroup = (String) valueChoose.getSelectedItem();
            String newGroup = valueInput.getText();
            boolean result = groupController.modifyGroup(new Group(oldGroup), new Group(newGroup));
            if (result) {
                JOptionPane.showMessageDialog(null, "修改成功");
            } else {
                JOptionPane.showMessageDialog(null, "修改失败");
            }
        }
        this.setVisible(false);
    }
}
